<template>
  <section v-loading.fullscreen.lock="loading" class="returnMain">
    <el-card class="margin-top">
      <div slot="header" class="clearfix relative small-header">
        <el-row>
          <el-col
            :sm="24"
            :md="24"
            :lg="12"
            :xl="12"
            class="flex  align-center justify-start"
          >
            <span class="title-icon margin-right">退货追踪信息</span>
            <el-button
              v-if="returnBatchIndex == 1"
              type="primary"
              size="mini"
              icon="el-icon-download"
              @click="downReturnTrackingInfo"
            >
              导出退货追踪信息
            </el-button>
            <el-button
              v-if="
                isEdit && verifyShow.returnInfoEdit && returnBatchIndex == 1
              "
              type="primary"
              size="mini"
              icon="el-icon-upload2"
              @click="uploadDialog = true"
            >
              导入退货追踪信息
            </el-button>
          </el-col>
          <el-col
            :sm="24"
            :md="24"
            :lg="12"
            :xl="12"
            class="flex text-blue align-center justify-between"
          >
            <div>
              <span class="margin-lr">总箱数：{{ totalAmount[0] }} </span>
              <span class="margin-lr">总产品个数：{{ totalAmount[1] }} </span>
              <span class="margin-lr">总签收托盘数：{{ totalAmount[2] }} </span>
              <span class="margin-lr">总签收箱数 ：{{ totalAmount[3] }} </span>
            </div>
            <div>
              <el-button
                v-if="isEdit && verifyShow.returnInfoEdit"
                type="primary"
                size="mini"
                @click="showTimeModal = true"
              >
                仓租计算
              </el-button>
              <el-button
                v-if="isEdit && verifyShow.returnInfoEdit"
                type="success"
                size="mini"
                @click="batchDel"
              >
                批量删除
              </el-button>
              <el-button
                v-if="!editTable && isEdit && verifyShow.returnInfoEdit"
                type="success"
                size="mini"
                @click="editTable = true"
              >
                编辑
              </el-button>
              <el-button
                v-if="editTable && isEdit && verifyShow.returnInfoEdit"
                type="success"
                size="mini"
                @click="editTable = false"
              >
                取消
              </el-button>
              <el-button
                v-if="editTable && isEdit && verifyShow.returnInfoEdit"
                type="success"
                size="mini"
                @click="changeCargoInfo"
              >
                保存
              </el-button>
              <i
                :class="{
                  'el-icon-arrow-down': show,
                  'el-icon-arrow-up': !show
                }"
                class="text-lg pointer margin-left"
                @click="show = !show"
              ></i>
            </div>
          </el-col>
        </el-row>
      </div>

      <div>
        <el-table
          v-show="show"
          ref="multipleTable"
          :header-cell-style="{ background: '#f5f9fc' }"
          size="mini"
          border
          :data="tableData"
          :span-method="objectSpanMethod"
          style="width: 100%;"
          class="margin-top "
          tooltip-effect="light"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="40" align="center" />

          <el-table-column
            v-for="column in tableColumns"
            :key="column.prop"
            :width="
              column.type == 'num'
                ? 80
                : column.prop == 'trackNo'
                ? 150
                : 'auto'
            "
            :prop="column.prop"
            :label="column.label"
          >
            <template slot-scope="scope" class="column-wrapper">
              <template v-if="column.type && column.type === 'boolean'">
                <el-select
                  v-if="verifyShow.returnInfoEdit && editTable"
                  v-model="scope.row[column.prop]"
                  placeholder="请选择"
                  size="mini"
                >
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
                <span v-else>
                  {{
                    scope.row[column.prop] == 0
                      ? "否"
                      : scope.row[column.prop]
                      ? "是"
                      : ""
                  }}
                </span>
              </template>
              <template v-else-if="column.prop === 'returnNo'">
                <!-- <span>{{ scope.row[column.prop] }}</span> -->
                <el-popover
                  placement="top-start"
                  trigger="hover"
                  :content="scope.row[column.prop]"
                >
                  <span slot="reference">{{ scope.row[column.prop] }}</span>
                </el-popover>
              </template>
              <template v-else>
                <el-input
                  v-if="verifyShow.returnInfoEdit && editTable"
                  v-model="scope.row[column.prop]"
                  size="mini"
                />
                <span v-else>{{ scope.row[column.prop] }}</span>
              </template>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="60" align="center">
            <template slot-scope="scope">
              <i
                class="el-icon-delete padding-lr-sm pointer"
                @click="colDel(scope.row)"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="text-blue margin-top-sm text-center">
        <span class="margin-right"
          >一个追踪号填写一单元格，请勿将多个追踪号混在同一单元格。</span
        >
        <span
          >新增退货跟踪号时，请先导出模板，在表格的原跟踪号后加上更新的跟踪号再导入系统即可，注意不要删掉之前的信息</span
        >
      </div>
    </el-card>
    <ImportPop
      :uploadDialog.sync="uploadDialog"
      :actionUrl="`batchUploadReturnTrackData`"
      :waybillId="waybillId"
      @uploadCb="uploadReturnTrackData"
    ></ImportPop>

    <el-dialog title="费用日期" :visible.sync="showTimeModal" width="20%">
      <el-form :model="form" ref="timeForm">
        <el-form-item
          label=""
          prop="costTime"
          :rules="[
            {
              required: true,
              message: '日期不能为空',
              trigger: ['blur', 'change']
            }
          ]"
        >
          <el-date-picker
            size="mini"
            v-model="form.costTime"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="enterClick">确 定</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import { ajax } from "@/store/yg/common/utils";
import ImportPop from "./ImportPop";
import { clone } from "@/utils/clone";
import "handsontable/languages/zh-CN";
import globalData from "@/utils/config";
import * as constant from "@/store/yg/common/constant";
import { checkRowsEmpty } from "@/utils";
export default {
  name: "OrderToOrderToOverseasWarehouseShipping",
  components: {
    ImportPop
  },
  props: {
    returnTrackingInfo: {
      type: Array,
      default: function() {
        return [];
      }
    },
    oldReturnTrackingInfo: {
      type: Array,
      default: function() {
        return [];
      }
    },
    margeList: {
      type: Array,
      default: function() {
        return [];
      }
    },
    actionUrl: {
      type: String,
      default: ""
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    returnBatchIndex: {
      type: Number,
      default: 1
    },
    waybillId: {
      type: Number,
      default: 1
    },
    verifyShow: {
      type: Object,
      default: function() {
        return {};
      }
    }
  },
  watch: {
    show: {
      handler(val) {}
    },
    returnTrackingInfo(newValue, oldValue) {
      console.log("returnTrackingInfo :>> ", newValue);
      if (newValue.length !== 0) {
        this.tableData = clone(newValue);
        this.getSpanArr(this.tableData);
      }
    }
  },
  data() {
    return {
      editTable: false,
      show: false,
      loading: false,
      // totalAmount: [0, 0, 0, 0],
      uploadDialog: false,
      autoHeight: "auto",
      waybillGoodsInfos: [{}, {}, {}, {}, {}],
      showTimeModal: false,
      form: {
        costTime: ""
      },
      options: [
        {
          value: 1,
          label: "是"
        },
        {
          value: 0,
          label: "否"
        }
      ],
      multipleSelection: [],
      tableData: [],
      spanArr: [],
      pos: 0,
      tableColumns: [
        {
          prop: "returnNo",
          label: "退货编号"
        },
        {
          prop: "trackNo", // 指定所指列
          label: "退货追踪号"
        },
        {
          prop: "shipmentId",
          label: "Shipment ID"
        },
        {
          prop: "cartons",
          label: "箱数",
          type: "num"
        },
        {
          prop: "receiptDate",
          label: "仓库签收日期"
        },
        {
          prop: "receiptPallets",
          label: "签收托盘数",
          type: "num"
        },
        {
          prop: "receiptCartons",
          label: "签收箱数",
          type: "num"
        },
        {
          prop: "sku",
          label: "旧FNSKU"
        },
        {
          prop: "num",
          label: "产品个数(PCS)"
        },
        {
          prop: "receiptQuantity",
          label: "签收个数",
          type: "num"
        },
        {
          prop: "location",
          label: "Location"
        },
        {
          prop: "boxSpecifications",
          label: "Size"
        },
        {
          prop: "receiptCondition",
          label: "签收情况（是否有破损）",
          type: "boolean"
        }
      ]
    };
  },

  computed: {
    totalAmount() {
      let cartons = 0;
      let num = 0;
      let receiptPallets = 0;
      let receiptCartons = 0;

      const arr = [];
      for (const i of this.returnTrackingInfo) {
        if (i.trackNo && !arr.includes(i.trackNo)) {
          arr.push(i.trackNo);
          if (i.cartons) {
            cartons += parseInt(i.cartons);
          }
          if (i.receiptPallets) {
            receiptPallets += parseInt(i.receiptPallets);
          }
          if (i.receiptCartons) {
            receiptCartons += parseInt(i.receiptCartons);
          }
        }
        if (i.num) {
          num += parseInt(i.num);
        }
      }
      return [cartons, num, receiptPallets, receiptCartons];
    }
  },
  mounted() {
    if (this.returnTrackingInfo.length > 0) {
      console.log("this.returnTrackingInfo: ", this.returnTrackingInfo);
      this.tableData = this.returnTrackingInfo;
      this.getSpanArr(this.tableData);
    }
  },
  methods: {
    // 计算表格合并
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if ([0, 1, 2, 3, 4, 5, 6, 7].includes(columnIndex)) {
        // 关键字段  shipmentId 一定要存在
        const target = this.returnTrackingInfo.find(
          x => x.returnNo === row.returnNo
        );
        // console.log('target.spanArr[rowIndex] :>> ', target.spanArr[rowIndex])
        const row_span =
          target && (this.spanArr[rowIndex] || this.spanArr[rowIndex] === 0)
            ? this.spanArr[rowIndex]
            : 1;
        return {
          rowspan: row_span,
          colspan: 1
        };
      }
    },
    getSpanArr(arr) {
      // 数据排序，以便合并

      if (arr && arr.length > 0) {
        let spanArr = [];
        let pos = 0;

        arr.sort((a, b) => parseFloat(a.sortNo) - parseFloat(b.sortNo));
        spanArr = [];
        pos = 0;
        for (var i = 0; i < arr.length; i++) {
          if (i === 0) {
            spanArr.push(1);
            pos = 0;
          } else {
            // 判断当前元素与上一个元素是否相同,因合并第一个所以[0]
            if (arr[i]["trackNo"] === arr[i - 1]["trackNo"]) {
              spanArr[pos] += 1;
              spanArr.push(0);
            } else {
              spanArr.push(1);
              pos = i;
            }
          }
        }
        this.spanArr = spanArr;
        // console.log('%cspanArr: ', 'color: #fff; background: #ccc;', spanArr)
        this.pos = pos;
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    async batchDel() {
      if (this.multipleSelection.length === 0) {
        this.$message.error("请选择要删除的数据");
        return;
      }
      const ids = [];
      for (const s of this.multipleSelection) {
        ids.push(s.id);
      }

      this.$confirm("删除该信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          this.$store.dispatch("app/toggleDialog", true);

          const res = await ajax("batchDeleteReturnReceive", {
            ids: ids
          });
          if (res.code === 200) {
            this.$message({
              message: "操作成功",
              type: "success"
            });
            this.uploadReturnTrackData();
          } else {
            this.$message.error(res.message || "操作失败");
          }
          this.$store.dispatch("app/toggleDialog", false);
        })
        .catch(() => {});
    },
    async colDel(row) {
      this.$confirm("删除该信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          this.$store.dispatch("app/toggleDialog", true);

          const res = await ajax("deleteAbroadSku", {
            id: row.skuId
          });
          if (res.code === 200) {
            this.$message({
              message: "操作成功",
              type: "success"
            });
            this.uploadReturnTrackData();
          } else {
            this.$message.error(res.message || "操作失败");
          }
          this.$store.dispatch("app/toggleDialog", false);
        })
        .catch(() => {});
    },
    closeDialog() {
      this.uploadDialog = false;
    },
    async downReturnTrackingInfo() {
      const { path, fileName } = await ajax("downLoadReturnTrack", {
        id: this.waybillId
      });
      if (fileName) {
        window.open(constant.FILE_SERVER + fileName);
      }
    },
    uploadReturnTrackData(file) {
      // console.log("uploadCargoInfo", file);
      this.$emit("getReturnInfo");
      this.$emit("getOperation");
    },
    changeCargoInfo() {
      const h = this.tableData.filter(x => checkRowsEmpty(x));
      console.log("h :>> ", h);
      if (h.length === 0) {
        this.$message.error("数据为空！");
        return;
      }
      for (const i of h) {
        if (!i.trackNo || !i.sku || !i.num) {
          this.$message.error("请填写必填信息");
          return;
        }
        if (i.cartons && !this.Number(i.cartons)) {
          this.$message.error("箱数，请填写整数");
          return;
        }
        if (i.num && !this.Number(i.num)) {
          this.$message.error("数量，请填写整数");
          return;
        }
        if (i.receiptPallets && !this.Number(i.receiptPallets)) {
          this.$message.error("签收托盘数，请填写整数");
          return;
        }
        if (i.receiptCartons && !this.Number(i.receiptCartons)) {
          this.$message.error("签收箱数，请填写整数");
          return;
        }

        if (!i.waybillId) {
          i.waybillId = this.waybillId;
        }

        i.abroadSkuList = [
          {
            id: i.skuId || "",
            sku: i.sku,
            num: i.num,
            returnReceiveId: i.returnReceiveId,
            receiptQuantity: i.receiptQuantity,
            location: i.location,
            receiptCondition: i.receiptCondition
          }
        ];
      }
      this.saveInfo(h);
    },
    Number(val) {
      if (parseInt(val).toString() == "NaN") {
        return false;
      } else {
        return true;
      }
    },
    async saveInfo(h) {
      // 标记已删除数据
      const { code, message } = await ajax("batchUpdateReturnReceiveGoods", {
        receiveGoods: h
      });
      this.loading = false;
      if (code === 200) {
        this.$message({
          type: "success",
          message: "保存成功"
        });
      } else {
        this.$message.error(message || "保存失败！");
      }
    },
    cancel() {
      this.showTimeModal = false;
      this.form = {
        costTime: ""
      };
    },
    enterClick() {
      this.$refs.timeForm.validate(valid => {
        if (valid) {
          this.countAbraodStock();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    async countAbraodStock() {
      this.loading = true;
      this.form.waybillId = this.waybillId;
      const { code, message } = await ajax("countAbraodStock", this.form);
      if (code === 200) {
        this.$message.success("操作成功！");
      } else {
        this.$message.error(message || "操作失败！");
      }
      this.showTimeModal = false;
      this.loading = false;
    }
  }
};
</script>

<style lang="scss" scoped></style>
<style scoped>
/deep/ .el-card__header {
  padding: 8px 20px;
}

.header-save-btn {
  top: 0%;
}

/* /deep/ .el-table .cell,
.el-table th > .cell {
  padding: 0;
}

/deep/ .el-table .cell,
.el-table--border td:first-child .cell,
.el-table--border th:first-child .cell {
  padding: 0;
} */

/deep/ .cell .el-input__inner {
  padding: 0;
}
</style>
